use std::fs::File;
use std::io::{self, prelude::*, BufReader};
#[macro_use] extern crate lazy_static;
extern crate regex;
use regex::Regex;

fn main() -> io::Result<()>{
    let input = File::open("input.txt")?;
    let reader = BufReader::new(input);
    let mut valid_password_rule_1 = 0;
    let mut valid_password_rule_2 = 0;
    let mut password_number = 0;
    lazy_static!{
        static ref RE: Regex = Regex::new("(\\d+)-(\\d+) (\\w): ([a-z]+)").unwrap();
    }
    for line in reader.lines() {
        let str = line?;
        let cap  = RE.captures(&str).unwrap();
        let matches: Vec<&str> = (&cap[4]).matches(&cap[3]).collect();
        let occurences = matches.len();
        let nu_1 = (&cap[1]).parse::<usize>().unwrap();
        let nu_2 = (&cap[2]).parse::<usize>().unwrap();
        password_number += 1;
        // Password rule 1
        if occurences >= nu_1 && occurences <= nu_2 {
            valid_password_rule_1 += 1;
        }
        // Password rule 2
        let letter = (&cap[3]).chars().next().unwrap();
        let rule_2_validity = ((&cap[4]).chars().nth(nu_2 - 1).unwrap() == letter) ^
                              ((&cap[4]).chars().nth(nu_1 - 1).unwrap() == letter);
        if rule_2_validity {
            valid_password_rule_2 += 1;
        }
        
    }
    println!("There are {}/{} valid passwords following rule 1", valid_password_rule_1, password_number);
    println!("There are {}/{} valid passwords following rule 2", valid_password_rule_2, password_number);

    Ok(())
}
